package com.tuanzi.loan.business.service.businesssystem.impl;

import com.tuanzi.loan.business.entity.businesssystem.*;
import com.tuanzi.loan.business.repository.businesssystem.BusinessMainRepository;
import com.tuanzi.loan.business.repository.businesssystem.BusinessProductRepository;
import com.tuanzi.loan.business.service.businesssystem.BusinessMainService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.repository.JPAAuditRepository;
import com.tuanzi.loan.core.service.BaseAuditServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.businesssystem.BusinessMainRequest;
import com.tuanzi.loan.vo.response.businesssystem.BusinessMainResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Debug
@Service
@Transactional
@Retryable(value = {RetryException.class})
public class BusinessMainServiceImpl extends BaseAuditServiceImpl<BusinessMain,Long> implements BusinessMainService {
    @Autowired
    private BusinessMainRepository repository;
    @Autowired
    private BusinessProductRepository businessProductRepository;

    @Override
    public Page<BusinessMainResponse> list(PageSearcher<BusinessMainRequest> pageSearcher) {
        return repository.list(pageSearcher.getSearchCondition(),pageSearcher.getPageable());
    }

    @Override
    public List<BusinessMain> getCompanyList() {
        return repository.getCompanyList();
    }

    @Override
    public void billDelete(BusinessBill billAmount) {
        BusinessMain one = repository.getOne(billAmount.getCompanyId());
        one.setBillAmount(one.getBillAmount()-billAmount.getBillAmount());
        repository.save(one);
    }

    @Override
    public void prepayDelete(BusinessPrepay prepay) {
        BusinessMain one = repository.getOne(prepay.getCompanyId());
        one.setBillAmount(one.getBillAmount()-prepay.getPrepayAmount());
        repository.save(one);
    }

    @Override
    public void incomeDelete(BusinessIncome income) {
        BusinessProduct product = businessProductRepository.findByChannelId(income.getChannelId());
        BusinessMain one = repository.getOne(product.getCompanyId().longValue());
        one.setExpendAmount(one.getExpendAmount()-income.getIncomeAmount());
        repository.save(one);
    }

    @Override
    protected JPAAuditRepository<BusinessMain, Long> getRepository() {
        return repository;
    }
}
